package com.topnav.mc.admin.security.jwt.handle;

import com.alibaba.fastjson2.JSON;
import com.js.lib.cache.SysCache;
import com.js.lib.result.Result;
import com.topnav.mc.admin.entity.enums.EnumLogType;
import com.topnav.mc.admin.entity.enums.EnumOperateFunction;
import com.topnav.mc.admin.security.config.JwtProperties;
import com.topnav.mc.admin.service.IOperateLogService;
import com.topnav.mc.common.Constant;
import com.topnav.mc.uitls.PermissionGradeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * 登录成功
 */
@Component
@Slf4j
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private SysCache sysCache;
    @Resource
    private JwtProperties jwtProperties;
    @Resource
    private PermissionGradeUtil permissionGradeUtil;
    @Autowired
    private IOperateLogService operateLogService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        operateLogService.saveLog(EnumLogType.LOGOUT, EnumOperateFunction.SYSTEM);

        String tokenStr = request.getHeader(jwtProperties.getHeader());
        if (StringUtils.isEmpty(tokenStr)){
            tokenStr = request.getParameter(jwtProperties.getHeader());
        }
        /** 删除 权限 级别的记录*/
        if (!StringUtils.isEmpty(tokenStr))
            permissionGradeUtil.removePmGrade(tokenStr);

        String json =  JSON.toJSONString(Result.ok("注销成功"));
        // 允许跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 允许自定义请求头token(允许head跨域)
        response.setHeader("Access-Control-Allow-Headers", "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");

        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(json);
    }
}
